package com.xuedongzhilian.controller;

import com.xuedongzhilian.dto.Result;
import com.xuedongzhilian.dto.ForumPostDTO;
import com.xuedongzhilian.entity.ForumPost;
import com.xuedongzhilian.service.IForumPostService;
import com.xuedongzhilian.utils.UserHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 论坛帖子控制器
 * </p>
 *
 * @author 学动智联团队
 * @since 2025-10-14
 */
@Slf4j
@RestController
@RequestMapping("/forum-post")
public class ForumPostController {

    @Resource
    private IForumPostService forumPostService;

    /**
     * 发布帖子
     */
    @PostMapping
    public Result publishPost(@RequestBody ForumPostDTO forumPostDTO) {
        ForumPost forumPost = new ForumPost();
        BeanUtils.copyProperties(forumPostDTO, forumPost);
        forumPost.setUserId(UserHolder.getUser().getId());
        forumPost.setViewCount(0);
        forumPost.setLikeCount(0);
        forumPost.setCommentCount(0);
        forumPost.setCollectCount(0);
        forumPost.setStatus(1); // 正常状态
        forumPost.setCreateTime(LocalDateTime.now());
        forumPost.setUpdateTime(LocalDateTime.now());
        
        boolean success = forumPostService.save(forumPost);
        if (success) {
            return Result.ok(forumPost);
        } else {
            return Result.fail("发布失败");
        }
    }

    /**
     * 获取帖子列表
     */
    @GetMapping
    public Result getPosts(@RequestParam(required = false) String keyword,
                          @RequestParam(defaultValue = "1") Integer current,
                          @RequestParam(defaultValue = "10") Integer size) {
        List<ForumPost> posts = forumPostService.lambdaQuery()
                .like(keyword != null && !keyword.isEmpty(), ForumPost::getTitle, keyword)
                .or()
                .like(keyword != null && !keyword.isEmpty(), ForumPost::getContent, keyword)
                .eq(ForumPost::getStatus, 1) // 只获取正常状态的帖子
                .orderByDesc(ForumPost::getCreateTime)
                .page(new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(current, size))
                .getRecords();
                
        return Result.ok(posts);
    }

    /**
     * 获取帖子详情
     */
    @GetMapping("/{id}")
    public Result getPostDetail(@PathVariable Long id) {
        ForumPost post = forumPostService.getById(id);
        if (post == null || post.getStatus() != 1) {
            return Result.fail("帖子不存在或已被删除");
        }
        
        // 增加浏览数
        post.setViewCount(post.getViewCount() + 1);
        forumPostService.updateById(post);
        
        return Result.ok(post);
    }

    /**
     * 点赞帖子
     */
    @PostMapping("/like/{id}")
    public Result likePost(@PathVariable Long id) {
        ForumPost post = forumPostService.getById(id);
        if (post == null || post.getStatus() != 1) {
            return Result.fail("帖子不存在或已被删除");
        }
        
        post.setLikeCount(post.getLikeCount() + 1);
        post.setUpdateTime(LocalDateTime.now());
        
        boolean success = forumPostService.updateById(post);
        if (success) {
            return Result.ok("点赞成功");
        } else {
            return Result.fail("点赞失败");
        }
    }

    /**
     * 收藏帖子
     */
    @PostMapping("/collect/{id}")
    public Result collectPost(@PathVariable Long id) {
        ForumPost post = forumPostService.getById(id);
        if (post == null || post.getStatus() != 1) {
            return Result.fail("帖子不存在或已被删除");
        }
        
        post.setCollectCount(post.getCollectCount() + 1);
        post.setUpdateTime(LocalDateTime.now());
        
        boolean success = forumPostService.updateById(post);
        if (success) {
            return Result.ok("收藏成功");
        } else {
            return Result.fail("收藏失败");
        }
    }

    /**
     * 删除帖子
     */
    @DeleteMapping("/{id}")
    public Result deletePost(@PathVariable Long id) {
        Long userId = UserHolder.getUser().getId();
        ForumPost post = forumPostService.getById(id);
        
        if (post == null) {
            return Result.fail("帖子不存在");
        }
        
        if (!post.getUserId().equals(userId)) {
            return Result.fail("无权删除该帖子");
        }
        
        // 软删除，将状态改为已删除
        post.setStatus(3);
        post.setUpdateTime(LocalDateTime.now());
        
        boolean success = forumPostService.updateById(post);
        if (success) {
            return Result.ok("删除成功");
        } else {
            return Result.fail("删除失败");
        }
    }
}